import { defineStore } from 'pinia'
import { ref, onMounted } from 'vue'

// 定义 Store
export const useSign = defineStore(
  'sign',
  () => {
    const sign = ref()

    const setsign = (val: string) => {
      sign.value = val
    }

    // 清理会员信息，退出时使用
    const clearsign = () => {
      sign.value = undefined
    }

    // 每天0点自动调用clearsign
    const autoClearSignAtMidnight = () => {
      const currentHour = new Date().getHours();
      if (currentHour === 0) {
        clearsign()
      } else {
        const delayUntilMidnight = (24 - currentHour) * 60 * 60 * 1000
        setTimeout(autoClearSignAtMidnight, delayUntilMidnight)
      }
    }

    // 在组件挂载时启动定时器
    onMounted(() => {
      autoClearSignAtMidnight()
    })
    return {
      sign,
      setsign,
      clearsign,
      autoClearSignAtMidnight,
    }
  },
  // TODO: 持久化
  {
    //小程序的配置

    persist: {
      storage: {
        getItem(key) {
          return uni.getStorageSync(key)
        },
        setItem(key, value) {
          uni.setStorageSync(key, value)
        },
      },
    },
  },
)
